//
//  EMShoppingCartViewController.m
//  ElectronicMall
//
//  Created by 史伟文 on 14/12/21.
//  Copyright (c) 2014年 cczu. All rights reserved.
//

#import "EMShoppingCartViewController.h"
#import "UINavigationController+EMNavi.h"
#import "EMShoppingCartCell.h"
#import "EMConfirmViewController.h"
#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "EMShoppingCartReqBody.h"
#import "EMShoppingCartRespBody.h"
#import "EMRecountReqBody.h"
#import "EMRecountRespBody.h"
#import "EMRemoveCartReqBody.h"
#import "EMRemoveCartRespBody.h"
#import "EMGoodInfo.h"

#import "EMGetScoreReqBody.h"
#import "EMGetScoreRespBody.h"
#import "EMSettleReqBody.h"
#import "EMSettleRespBody.h"
#import "UserInfo.h"
#import "EMLoginViewController.h"
#import "UIImageView+WebCache.h"

@interface EMShoppingCartViewController ()
{
    AppDelegate *app;
    UITableView *newGoodTable;
    BOOL isEditing;
    float totalPrice;
    UILabel *totalLabel;
    
    NSMutableArray *goodList;
    int chooseFlag;
    NSMutableArray *flagArray;
    
    NSString *score;
    NSString *balance;
    
}
@end

@implementation EMShoppingCartViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [self.navigationController setNavigationMode:EMNavigationModeDefault andSubMode:0];
    self.navigationItem.title = @"购物车";
    isEditing = NO;
    totalPrice = 0.0f;
    flagArray = [NSMutableArray array];

    
    UIButton *button =[UIButton buttonWithType:UIButtonTypeCustom];
    button.frame=CGRectMake(0, 0, 40, 32);
    button.titleLabel.font = [UIFont fontWithName:HEITILIGHT size:16];
    [button setTitle:@"编辑" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(editAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item =[[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.rightBarButtonItem =item;
    
    
    if ([UserInfo sharedUserInfo].m_isLogin) {
        [goodList removeAllObjects];
        [self getCartData];
        
        [self getTotalPrice];
        [newGoodTable reloadData];
    } else {
        [app showTip:@"请先登录"];
        return;
    }

}

- (void)getCartData
{
    [MBProgressHUD  showHUDAddedTo:self.navigationController.view animated:YES];
    EMShoppingCartReqBody *reqBody = [[EMShoppingCartReqBody alloc] init];
    reqBody.JUDGEMETHOD = @"SHOPPING-CART";
    reqBody.NAME = [UserInfo sharedUserInfo].m_userName;
    reqBody.SESSION = [UserInfo sharedUserInfo].m_session;
    HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
    request.postData = reqBody.keyValues;
    [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
        EMShoppingCartRespBody *respBody = [EMShoppingCartRespBody objectWithKeyValues:respInfo];
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        NSLog(@"%@", respInfo);
        if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
            goodList = [respBody.GOODINFO mutableCopy];
            
            for (int i = 0; i < goodList.count; i ++) {
                [flagArray addObject:@YES];
            }
            [self createView];
        } else {
            [app showTip:respInfo[@"ERRORDESTRIPTION"]];
        }
        
    } andFailedBlock:^{
        
        [app showTip:@"无法连接服务器、请稍后再试"];
    }];
}
- (void)getTotalPrice
{
    totalPrice = 0;
    if (goodList.count && flagArray.count) {
        for (int i = 0; i < goodList.count; i ++) {
            EMGoodInfo *goodInfo = [[EMGoodInfo alloc] initWithGoodInfo:goodList[i]];
            totalPrice += [goodInfo.m_count floatValue] * [goodInfo.m_nowPrice floatValue]  * [flagArray[i] intValue];
            totalLabel.text = [NSString stringWithFormat:@"%.2lf", totalPrice];
        }
    }
    
}
- (void)createView
{
    CGRect tableRect = [UIScreen mainScreen].bounds;
    tableRect.origin.y = tableRect.origin.y + 64;
    tableRect.size.height = tableRect.size.height - 50-64-49;
    newGoodTable = [[UITableView alloc] initWithFrame:tableRect style:UITableViewStylePlain];
    newGoodTable.delegate = self;
    newGoodTable.dataSource = self;
    newGoodTable.backgroundColor = RGB(242, 242, 242);
    newGoodTable.autoresizesSubviews = YES;
    [self.view addSubview:newGoodTable];
    
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 49 - 50, W(320), 50)];
    bottomView.backgroundColor = [UIColor whiteColor];
    
    
    
    
    
    UILabel *totalPriceTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 30)];
    totalPriceTitleLabel.text = @"总计金额：";
    [bottomView addSubview:totalPriceTitleLabel];
    
    totalLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 10, 100, 30)];
    [self getTotalPrice];
    [bottomView addSubview:totalLabel];
    
    UIButton *gotoCalculateButton = [UIButton buttonWithType:UIButtonTypeCustom];
    gotoCalculateButton.frame = CGRectMake(W(220), 10, W(80), 30);
    gotoCalculateButton.layer.backgroundColor = [UIColor redColor].CGColor;
    gotoCalculateButton.layer.cornerRadius = 5;
    [gotoCalculateButton setTitle:@"去结算" forState:UIControlStateNormal];
    [gotoCalculateButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [gotoCalculateButton addTarget:self action:@selector(gotoCalculateAction:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:gotoCalculateButton];
    
    [self.view addSubview:bottomView];
}
- (void)editAction: (UIButton *)sender
{
    if (isEditing) {
        [UIView animateWithDuration:0.3 animations:^{
            newGoodTable.editing = NO;
        }];
    } else {
        [UIView animateWithDuration:0.3 animations:^{
            newGoodTable.editing = YES;
        }];

    }
    isEditing = !isEditing;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    [self createView];
}


- (void)gotoCalculateAction:(UIButton *)sender
{
    if (goodList.count) {
        [self getUserScore];
        
        
        NSMutableArray *goodArray = [NSMutableArray array];
        for (int i = 0; i < goodList.count; i ++) {
            EMGoodInfo *goodInfo = [[EMGoodInfo alloc] initWithGoodInfo:goodList[i]];
            [goodArray addObject:@{@"id":goodInfo.m_id, @"no":goodInfo.m_count}];
        }
        
        [MBProgressHUD  showHUDAddedTo:self.navigationController.view animated:YES];
        EMSettleReqBody *reqBody = [[EMSettleReqBody alloc] init];
        reqBody.JUDGEMETHOD = @"ORDER-INFORMATION";
        reqBody.USERID = [UserInfo sharedUserInfo].m_userName;
        reqBody.SESSION = [UserInfo sharedUserInfo].m_session;
        reqBody.BUYGOODSINFO = [goodArray mutableCopy];
        HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
        request.postData = reqBody.keyValues;
        [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
            EMSettleRespBody *respBody = [EMSettleRespBody objectWithKeyValues:respInfo];
            [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
            NSLog(@"%@", respInfo);
            if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
                EMConfirmViewController *controller = [[EMConfirmViewController alloc] init];
                controller.hidesBottomBarWhenPushed = YES;
                controller.goodList = respBody;
                
                if (score) {
                    controller.score = score;
                }
                if (balance) {
                    controller.balance = balance;
                }
                [self.navigationController pushViewController:controller animated:YES];
                
            } else {
                [app showTip:respInfo[@"ERRORDESTRIPTION"]];
            }
            
        } andFailedBlock:^{
            
            [app showTip:@"无法连接服务器、请稍后再试"];
        }];

    }
    
}

- (void)chooseStateChanged:(UIButton *)sender
{
    totalPrice = 0;

    if ([flagArray[sender.tag - 1400] isEqualToNumber:@NO]) {
        [flagArray replaceObjectAtIndex:sender.tag - 1400 withObject:@YES];
        sender.alpha = 1.0f;

    } else {
        [flagArray replaceObjectAtIndex:sender.tag - 1400 withObject:@NO];
        sender.alpha = 0.1f;
    }
    [self getTotalPrice];
    [newGoodTable reloadData];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    EMGoodInfo *goodInfo = [[EMGoodInfo alloc] initWithGoodInfo:goodList[textField.tag - 1200]];
    
    [MBProgressHUD  showHUDAddedTo:self.navigationController.view animated:YES];
    EMRecountReqBody *reqBody = [[EMRecountReqBody alloc] init];
    reqBody.JUDGEMETHOD = @"MODIFY-SHOPPING-CART";
    reqBody.USERID = [UserInfo sharedUserInfo].m_userName;
    reqBody.SESSION = [UserInfo sharedUserInfo].m_session;
    reqBody.ID = goodInfo.m_id;
    reqBody.NUM = textField.text;
    HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
    request.postData = reqBody.keyValues;
    [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
        EMRecountRespBody *respBody = [EMRecountRespBody objectWithKeyValues:respInfo];
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        NSLog(@"%@", respInfo);
        if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
            totalPrice = 0;
            [self getCartData];
            [self getTotalPrice];
            [newGoodTable reloadData];
            
        } else {
            totalPrice = 0;
            [app showTip:respInfo[@"ERRORDESTRIPTION"]];
            [newGoodTable reloadData];
        }
        
    } andFailedBlock:^{
        
        [app showTip:@"无法连接服务器、请稍后再试"];
    }];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return goodList.count;
}

- (EMShoppingCartCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"cartCell";
    EMShoppingCartCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    EMGoodInfo *goodInfo = [[EMGoodInfo alloc] initWithGoodInfo:goodList[indexPath.row]];
    if (cell == nil) {
        cell = [[EMShoppingCartCell alloc] initWithStyle:0 reuseIdentifier:cellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    } 
//    totalPrice += [goodInfo.m_count floatValue] * [goodInfo.m_nowPrice floatValue]  * [flagArray[indexPath.row] intValue];
//    totalLabel.text = [NSString stringWithFormat:@"%.2lf", totalPrice];
    
    cell.goodTitle.text = goodInfo.m_name;
    [cell.goodImage sd_setImageWithURL:[NSURL URLWithString:goodInfo.m_imgUrl]];
    if ([goodInfo.m_mode intValue] == 0) {
        cell.goodDesc.text = @"";
        cell.originPrice.text = @"";
        cell.nowPrice.text = [NSString stringWithFormat:@"¥%@", goodInfo.m_nowPrice];
    } else {
        cell.goodDesc.text = goodInfo.m_goodDesc;
        NSMutableAttributedString *oPrice = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"¥%@", goodInfo.m_originPrice]];
        [oPrice addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, goodInfo.m_originPrice.length+1)];
        [oPrice addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, goodInfo.m_originPrice.length + 1)];
        cell.originPrice.attributedText = oPrice;
        cell.nowPrice.text = [NSString stringWithFormat:@"¥%@", goodInfo.m_nowPrice];
    }
    cell.countTextField.text = goodInfo.m_count;
    cell.countTextField.delegate = self;
    cell.countTextField.tag = indexPath.row + 1200;
//    [cell.countTextField addTarget:self action:@selector(countChanged:) forControlEvents:UIControlEventValueChanged];
    cell.chooseButton.tag = indexPath.row + 1400;
    if (flagArray.count) {
        cell.chooseButton.alpha = [flagArray[indexPath.row] isEqualToNumber:@YES] ? 1.0f : 0.1f;
    }
    
    [cell.chooseButton addTarget:self action:@selector(chooseStateChanged:) forControlEvents:UIControlEventTouchUpInside];
    
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    EMGoodInfo *goodInfo = [[EMGoodInfo alloc] initWithGoodInfo:goodList[indexPath.row]];
    
    [MBProgressHUD  showHUDAddedTo:self.navigationController.view animated:YES];
    EMRemoveCartReqBody *reqBody = [[EMRemoveCartReqBody alloc] init];
    reqBody.JUDGEMETHOD = @"DELETE-SHOPPING-CART";
    reqBody.ID = goodInfo.m_id;
    reqBody.NAME = [UserInfo sharedUserInfo].m_userName;
    reqBody.SESSION = [UserInfo sharedUserInfo].m_session;
    HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
    request.postData = reqBody.keyValues;
    [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
        EMRemoveCartRespBody *respBody = [EMRemoveCartRespBody objectWithKeyValues:respInfo];
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        NSLog(@"%@", respInfo);
        if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
            totalPrice = 0;
            [goodList removeObjectAtIndex:indexPath.row];
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
            [self getCartData];
            [tableView reloadData];
        } else {
            totalPrice = 0;
            [app showTip:respInfo[@"ERRORDESTRIPTION"]];
            [tableView reloadData];
        }
        
    } andFailedBlock:^{
        
        [app showTip:@"无法连接服务器、请稍后再试"];
    }];

}


#pragma mark - (next page)get Data
- (void)getUserScore
{
    [MBProgressHUD  showHUDAddedTo:self.navigationController.view animated:YES];
    EMGetScoreReqBody *reqBody = [[EMGetScoreReqBody alloc] init];
    reqBody.JUDGEMETHOD = @"USER-GET-SCORE";
    reqBody.USERID = [UserInfo sharedUserInfo].m_userName;
    reqBody.SESSION = [UserInfo sharedUserInfo].m_session;
    HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
    request.postData = reqBody.keyValues;
    [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
        EMGetScoreRespBody *respBody = [EMGetScoreRespBody objectWithKeyValues:respInfo];
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        NSLog(@"%@", respInfo);
        if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
            score = respBody.SCORE;
            balance = respBody.BALANCE;
        } else {
            [app showTip:respInfo[@"ERRORDESTRIPTION"]];
        }
        
    } andFailedBlock:^{
        
        [app showTip:@"无法连接服务器、请稍后再试"];
    }];
}

@end
